/**
 * Project Name:javaBaseReview
 * Package Name:com.xuwei.base.thread
 * author:David
 * Date:2015年8月20日下午4:18:54
 * Copyright (c) 2015, xw123box@126.com All Rights Reserved.
 *
 */
package com.xuwei.base.thread;

import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author David
 * @since 2015年8月20日 下午4:18:54
 * @version 
 * @since JDK 1.6
 */
public class ReadAndWriteLock {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final Queue queue=new Queue();
		for (int i = 0; i < 3; i++) {
			new Thread(){
				public void run() {
					while(true){
						queue.get();
					}
				};
			}.start();
			
			new Thread(){
				public void run() {
					while(true){
						try {
							Thread.sleep(500);
							queue.put(new Random().nextInt(1000));
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				};
			}.start();
			
		}
		
	}

}


class Queue{
	/*共享数据，只能有一个线程能写该数据，但可以有多个线程同时读该数据*/
	private Object data=null;
	final ReadWriteLock rwl=new ReentrantReadWriteLock();

	/**
	 * 
	 */
	public void get() {
		rwl.readLock().lock();
		try {
			System.out.println(Thread.currentThread().getName() + " be ready to read data!");
			Thread.sleep((long)(Math.random()*1000));
			System.out.println(Thread.currentThread().getName() + "have read data :" + data);			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			rwl.readLock().unlock();
		}
	}

	/**
	 * @param nextInt
	 */
	public void put(int data) {
		rwl.writeLock().lock();
		try {
			System.out.println(Thread.currentThread().getName() + " be ready to write data!");					
			Thread.sleep((long)(Math.random()*1000));
			this.data = data;		
			System.out.println(Thread.currentThread().getName() + " have write data: " + data);					
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			rwl.writeLock().unlock();
		}
	}
	
}
















